package handlers

import (
	"errors"
	"html/template"
	"strconv"
	"strings"

	"github.com/yjp211/web"

	"mutu/misc/conf"
	"mutu/misc/typedef"
	"mutu/models"
	"mutu/service"
)

type MatterView struct{}

var (
	MatterHandler = MatterView{}
)

func (p MatterView) CreateIndex(ctx *web.Context) {
	tags, _ := service.TagService.GetAllTags()
	cats, _ := service.CategoryService.GetAllCategorys()

	ses := ctx.Dict["session"].(*models.Session)
	pics, _ := service.ResourceService.GetUserResourceByFlag(conf.F_Resource_PIC, ses.UserId)
	psds, _ := service.ResourceService.GetUserResourceByFlag(conf.F_Resource_PSD, ses.UserId)
	shows, _ := service.ResourceService.GetUserResourceByFlag(conf.F_Resource_SHOW, ses.UserId)
	data := typedef.Dict{
		"tags":  tags,
		"cats":  cats,
		"pics":  pics,
		"psds":  psds,
		"shows": shows,
	}
	t, _ := template.ParseFiles("templates/matter-create.html")
	t.Execute(ctx, data)
}

func (p MatterView) ManageIndex(ctx *web.Context) {

	ses := ctx.Dict["session"].(*models.Session)
	binders, _ := service.BinderService.GetUserBinders(ses.UserId)
	pics, _ := service.MatterService.GetUserMattersByFlag(conf.F_Matter_PIC, ses.UserId)
	psds, _ := service.MatterService.GetUserMattersByFlag(conf.F_Matter_PSD, ses.UserId)
	service.MatterService.FillMattersInfo(pics, false, true, true, true)
	service.MatterService.FillMattersInfo(psds, false, true, true, true)
	data := typedef.Dict{
		"binders": binders,
		"pics":    pics,
		"psds":    psds,
	}
	t, _ := template.ParseFiles("templates/matter-manage.html")
	t.Execute(ctx, data)
}

func (p MatterView) EditIndex(ctx *web.Context) {

	uuid, ok := ctx.Params["uuid"]
	if !ok {
		ctx.Abort(401, "参数错误")
		return
	}
	matter, err := service.MatterService.GetMatterByUuid(uuid)
	if err != nil {
		ctx.Abort(500, err.Error())
		return
	}
	ses := ctx.Dict["session"].(*models.Session)
	if ses.UserId != matter.UserId {
		ctx.Abort(403, "没有权限")
		return
	}
	service.MatterService.FillMatterInfo(matter, false, true, true, true)
	tags, _ := service.TagService.GetAllTags()
	cats, _ := service.CategoryService.GetAllCategorys()
	data := typedef.Dict{
		"cats":       cats,
		"tags":       tags,
		"matter":     matter,
		"matterJson": PureJson(matter),
	}
	t, _ := template.ParseFiles("templates/matter-edit.html")
	t.Execute(ctx, data)
}

func (p MatterView) Create(ctx *web.Context) string {
	flag, err := strconv.Atoi(ctx.Params["flag"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	cat, err := strconv.Atoi(ctx.Params["categroy"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	tagstr, _ := ctx.Params["tags"]
	arr := strings.Split(tagstr, ",")
	tags := []int{}
	for _, item := range arr {
		tag, err := strconv.Atoi(item)
		if err == nil {
			tags = append(tags, tag)
		}
	}
	if len(tags) == 0 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	title, ok1 := ctx.Params["title"]
	desc, ok2 := ctx.Params["desc"]
	if !ok1 || !ok2 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	pic, ok1 := ctx.Params["pic"]
	show, ok2 := ctx.Params["show"]
	psd, ok3 := ctx.Params["psd"]
	score, err := strconv.Atoi(ctx.Params["score"])

	if flag == conf.F_Matter_PIC {
		if !ok1 {
			return JsonpReturn(ctx, nil, errors.New("参数错误"))
		}
		score = 0
		show = ""
		psd = ""
	} else if flag == conf.F_Matter_PSD {
		if !ok2 || !ok3 || err != nil {
			return JsonpReturn(ctx, nil, errors.New("参数错误"))
		}
		pic = ""
	} else {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	ses := ctx.Dict["session"].(*models.Session)

	matter := &models.Matter{
		Flag:   flag,
		Title:  title,
		Desc:   desc,
		Score:  score,
		PicId:  pic,
		ShowId: show,
		PsdId:  psd,
		UserId: ses.UserId,
	}
	err = service.MatterService.CreateMatter(cat, tags, matter)
	return JsonpReturn(ctx, nil, err)

}

func (p MatterView) Edit(ctx *web.Context) string {
	uuid, ok := ctx.Params["uuid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	flag, err := strconv.Atoi(ctx.Params["flag"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	cat, err := strconv.Atoi(ctx.Params["categroy"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	tagstr, _ := ctx.Params["tags"]
	arr := strings.Split(tagstr, ",")
	tags := []int{}
	for _, item := range arr {
		tag, err := strconv.Atoi(item)
		if err == nil {
			tags = append(tags, tag)
		}
	}
	if len(tags) == 0 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	title, ok1 := ctx.Params["title"]
	desc, ok2 := ctx.Params["desc"]
	if !ok1 || !ok2 {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	score, err := strconv.Atoi(ctx.Params["score"])

	if flag == conf.F_Matter_PIC {
		score = 0
	} else if flag == conf.F_Matter_PSD {
		if err != nil {
			return JsonpReturn(ctx, nil, errors.New("参数错误"))
		}
	} else {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	ses := ctx.Dict["session"].(*models.Session)

	matter := &models.Matter{
		Uuid:   uuid,
		Flag:   flag,
		Title:  title,
		Desc:   desc,
		Score:  score,
		UserId: ses.UserId,
	}
	err = service.MatterService.EditMatter(cat, tags, matter)
	return JsonpReturn(ctx, nil, err)

}

func (p MatterView) Delete(ctx *web.Context) string {
	uuid, ok := ctx.Params["uuid"]
	if !ok {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	ses := ctx.Dict["session"].(*models.Session)

	err := service.MatterService.DeleteMatter(ses.UserId, uuid)

	return JsonpReturn(ctx, nil, err)
}

func (p MatterView) All(ctx *web.Context) string {

	arr, err := service.MatterService.GetAllMatters()
	if err != nil {
		return JsonpReturn(ctx, nil, err)
	}
	service.MatterService.FillMattersInfo(arr, true, false, true, true)
	data := typedef.Dict{
		"matters": arr,
	}
	return JsonpReturn(ctx, data, nil)
}

func (p MatterView) AllByCat(ctx *web.Context) string {
	cat, err := strconv.Atoi(ctx.Params["cat"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	arr, err := service.MatterService.GetMattersByCat(cat)
	if err != nil {
		return JsonpReturn(ctx, nil, err)
	}
	service.MatterService.FillMattersInfo(arr, true, false, true, true)
	data := typedef.Dict{
		"matters": arr,
	}
	return JsonpReturn(ctx, data, nil)
}

func (p MatterView) AllByTag(ctx *web.Context) string {
	tag, err := strconv.Atoi(ctx.Params["tag"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}

	arr, err := service.MatterService.GetMattersByTag(tag)
	if err != nil {
		return JsonpReturn(ctx, nil, err)
	}
	service.MatterService.FillMattersInfo(arr, true, false, true, true)
	data := typedef.Dict{
		"matters": arr,
	}
	return JsonpReturn(ctx, data, nil)
}

func (p MatterView) GetCount(ctx *web.Context) string {
	flag, err := strconv.Atoi(ctx.Params["flag"])
	if err != nil {
		return JsonpReturn(ctx, nil, errors.New("参数错误"))
	}
	if flag == 1 {
		flag = conf.F_Matter_PIC
	} else if flag == 2 {
		flag = conf.F_Matter_PSD
	} else {
		flag = 0
	}

	count, err := service.MatterService.GetCount(flag)
	if err != nil {
		return JsonpReturn(ctx, nil, err)
	}
	data := typedef.Dict{
		"count": count,
	}
	return JsonpReturn(ctx, data, nil)
}
